package com.bbt.dormassistant.dao;

import com.bbt.dormassistant.entity.Questionnaire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class QuestionnaireDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    public Boolean save(Questionnaire questionnaire){
        try {
            return mongoTemplate.insert(questionnaire,"questionnaire") != null;
        }catch (Exception e){
            return false;
        }
    }

    public List<Questionnaire> findAll(){
        return mongoTemplate.findAll(Questionnaire.class);
    }

    public Questionnaire findByUserId(String userId){
        Query query = Query.query(Criteria.where("userId").is(userId));
        return mongoTemplate.findOne(query,Questionnaire.class);
    }

    public Boolean modifyByUserId(Questionnaire questionnaire){
        Query query = Query.query(Criteria.where("userId").is(questionnaire.getUserId()));
        return mongoTemplate.findAndReplace(query,questionnaire) != null;
    }
}
